package top.aigoo.project01.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.aigoo.project01.cache.JedisUtil;
import top.aigoo.project01.entity.HeadLine;
import top.aigoo.project01.mapper.HeadLineMapper;
import top.aigoo.project01.service.HeadLineService;

import javax.swing.*;
import java.io.IOException;
import java.util.*;

/**
 * @Description: HeadLine
 * 增加缓存的支持
 * @Author: Mr.OYSHUO.欧阳大叔  mail:1642302522@qq.com
 * @Version 1.0.0
 * @version 2.0  引入了redis
 * @Date: 2021/9/1 23:50
 */
@Service
public class HeadLineServiceImpl implements HeadLineService {
    @Autowired
    private HeadLineMapper headLineMapper;

    @Autowired
    private JedisUtil.Keys jedisKeys;

    @Autowired
    private JedisUtil.Strings jedisStrings;

    private static Logger logger = LoggerFactory.getLogger(HeadLineServiceImpl.class);

    @Override
    @Transactional
    public List<HeadLine> getHeadLineList(HeadLine headLineCondition) throws IOException {
        //定义redis的key的前缀
        String key = HLLISTKEY;
        //定义接收对象
        List<HeadLine> headLineList = null;
        //定义jackson数据转换操作类
        ObjectMapper mapper = new ObjectMapper();
        //拼接出redis的key,可能三种，分别为 headlinelist、headlinelist_1、headlinelist_0
        if (headLineCondition != null && headLineCondition.getEnableStatus() != null) {
            key = key + "_" + headLineCondition.getEnableStatus();
        }

        //判断key是否存在
        if (!jedisKeys.exists(key)) {//redis中不存在，则从数据库里面取出相应数据
            headLineList = headLineMapper.queryHeadLine(headLineCondition);
            //将相关实体类集合转换为string，存入redis里面对应的key中
            String jsonString = null;
            try {
                jsonString = mapper.writeValueAsString(headLineList);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            }
            jedisStrings.set(key, jsonString);
        } else {
            // 如果存在，则直接从redis里面取出相应数据
            String jsonString = jedisStrings.get(key);
            //指定要将string转换成集合类型
            JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, HeadLine.class);
            headLineList = mapper.readValue(jsonString, javaType);

        }
        return headLineList;
    }
}
